package com.zhihao.trigger.http;

import com.alibaba.fastjson.JSON;
import com.zhihao.domain.activity.service.quota.RaffleActivityAccountQuotaService;
import com.zhihao.domain.strategy.model.entity.RaffleAwardEntity;
import com.zhihao.domain.strategy.model.entity.RaffleFactorEntity;
import com.zhihao.domain.strategy.model.entity.StrategyAwardEntity;
import com.zhihao.domain.strategy.model.valobj.RuleWeightVO;
import com.zhihao.domain.strategy.service.IRaffleAward;
import com.zhihao.domain.strategy.service.IRaffleRule;
import com.zhihao.domain.strategy.service.IRaffleStrategy;
import com.zhihao.domain.strategy.service.armory.IStrategyArmory;
import com.zhihao.trigger.api.IRaffleStrategyService;
import com.zhihao.trigger.api.dto.*;
import com.zhihao.types.enums.ResponseCode;
import com.zhihao.types.exception.AppException;
import com.zhihao.types.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Jackson
 * @create 2025/3/17 9:08
 * @description 营销抽奖策略服务api-对外使用
 */
@Slf4j
@RestController
@CrossOrigin("${app.config.cross-origin}")
@RequestMapping("/api/${app.config.api-version}/raffle/strategy/")
@DubboService(version = "1.0")
public class RaffleStrategyController implements IRaffleStrategyService {

    @Resource
    private IStrategyArmory strategyArmory;

    @Resource
    private IRaffleStrategy raffleStrategy;

    @Resource
    private IRaffleAward raffleAward;

    @Resource
    private IRaffleRule raffleRule;

    @Resource
    private RaffleActivityAccountQuotaService raffleActivityAccountQuotaService;


    /**
     * 根据（用户id，活动id）查询奖品列表(userId用于判断奖品是否需要解锁)
     * <a href="http://localhost:8091/api/v1/raffle/strategy/query_raffle_award_list">/api/v1/raffle/query_raffle_award_list</a>
     * 请求参数 raw json
     *
     * @param request {"activityId":100301,"userId":"xiaofuge"}
     * @return 奖品列表
     *{
     * 	"code": "0000",
     * 	"info": "调用成功",
     * 	"data": [
     * 		        {
     * 			"awardId": 101,
     * 			"awardTitle": "随机积分",
     * 			"awardSubtitle": null,
     * 			"sort": 1,
     * 			"awardRuleLockCount": null,
     * 			"isAwardUnlock": true,
     * 			"waitUnLockCount": 0
     *        },
     *        {
     * 			"awardId": 102,
     * 			"awardTitle": "OpenAI会员卡",
     * 			"awardSubtitle": null,
     * 			"sort": 2,
     * 			"awardRuleLockCount": null,
     * 			"isAwardUnlock": true,
     * 			"waitUnLockCount": 0
     *        },
     *        {
     * 			"awardId": 103,
     * 			"awardTitle": "支付优惠券",
     * 			"awardSubtitle": null,
     * 			"sort": 3,
     * 			"awardRuleLockCount": null,
     * 			"isAwardUnlock": true,
     * 			"waitUnLockCount": 0
     *        },
     *        {
     * 			"awardId": 104,
     * 			"awardTitle": "小米台灯",
     * 			"awardSubtitle": null,
     * 			"sort": 4,
     * 			"awardRuleLockCount": null,
     * 			"isAwardUnlock": true,
     * 			"waitUnLockCount": 0
     *        },
     *        {
     * 			"awardId": 105,
     * 			"awardTitle": "小米su7周体验",
     * 			"awardSubtitle": "抽奖3次后解锁",
     * 			"sort": 5,
     * 			"awardRuleLockCount": 3,
     * 			"isAwardUnlock": false,
     * 			"waitUnLockCount": 2
     *        },
     *        {
     * 			"awardId": 106,
     * 			"awardTitle": "轻奢办公椅",
     * 			"awardSubtitle": "抽奖2次后解锁",
     * 			"sort": 6,
     * 			"awardRuleLockCount": 2,
     * 			"isAwardUnlock": false,
     * 			"waitUnLockCount": 1
     *        },
     *        {
     * 			"awardId": 107,
     * 			"awardTitle": "小霸王游戏机",
     * 			"awardSubtitle": "抽奖1次后解锁",
     * 			"sort": 7,
     * 			"awardRuleLockCount": 1,
     * 			"isAwardUnlock": true,
     * 			"waitUnLockCount": 0
     *        },
     *        {
     * 			"awardId": 108,
     * 			"awardTitle": "暴走玩偶",
     * 			"awardSubtitle": null,
     * 			"sort": 8,
     * 			"awardRuleLockCount": null,
     * 			"isAwardUnlock": true,
     * 			"waitUnLockCount": 0
     *        }
     * 	]
     * }
     *
     */
    @RequestMapping(value = "query_raffle_award_list", method = RequestMethod.POST)
    @Override
    public Response<List<RaffleAwardListResponseDTO>> queryRaffleAwardList(@RequestBody RaffleAwardListRequestDTO request) {
        try {
            log.info("查询抽奖奖品列表配开始 userId:{} activityId：{}", request.getUserId(), request.getActivityId());
            // 1. 参数校验
            if (StringUtils.isBlank(request.getUserId()) || null == request.getActivityId()) {
                throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
            }
            // 2. 查询奖品配置
            List<StrategyAwardEntity> strategyAwardEntities = raffleAward.queryRaffleStrategyAwardListByActivityId(request.getActivityId());
            // 3. 获取策略奖品的规则配置
            String[] treeIds = strategyAwardEntities.stream()
                    .map(StrategyAwardEntity::getRuleModels)
                    .filter(ruleModel -> ruleModel != null && !ruleModel.isEmpty()) // 去除掉rule_model为空的奖品
                    .toArray(String[]::new);
            // 4. 查询规则配置 - 获取奖品的解锁限制，抽奖N次后解锁
            Map<String, Integer> ruleLockCountMap = raffleRule.queryAwardRuleLockCount(treeIds);
            // 5. 查询抽奖次数 - 用户已经参与的抽奖次数
            Integer dayPartakeCount = raffleActivityAccountQuotaService.queryRaffleActivityAccountDayPartakeCount(request.getActivityId(), request.getUserId());
            // 6. 遍历填充数据
            List<RaffleAwardListResponseDTO> raffleAwardListResponseDTOS = new ArrayList<>(strategyAwardEntities.size());
            for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
                Integer awardRuleLockCount = ruleLockCountMap.get(strategyAward.getRuleModels());
                raffleAwardListResponseDTOS.add(RaffleAwardListResponseDTO.builder()
                        .awardId(strategyAward.getAwardId())
                        .awardTitle(strategyAward.getAwardTitle())
                        .awardSubtitle(strategyAward.getAwardSubtitle())
                        .sort(strategyAward.getSort())
                        .awardRuleLockCount(awardRuleLockCount)
                        .isAwardUnlock(null == awardRuleLockCount || dayPartakeCount >= awardRuleLockCount)
                        .waitUnLockCount((null == awardRuleLockCount || awardRuleLockCount <= dayPartakeCount) ? 0 : awardRuleLockCount - dayPartakeCount)
                        .build());
            }
            Response<List<RaffleAwardListResponseDTO>> response = Response.<List<RaffleAwardListResponseDTO>>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(raffleAwardListResponseDTOS)
                    .build();
            log.info("查询抽奖奖品列表配置完成 userId:{} activityId：{} response: {}", request.getUserId(), request.getActivityId(), JSON.toJSONString(response));
            // 返回结果
            return response;
        } catch (Exception e) {
            log.error("查询抽奖奖品列表配置失败 userId:{} activityId：{}", request.getUserId(), request.getActivityId(), e);
            return Response.<List<RaffleAwardListResponseDTO>>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

    /**
     * 查询抽奖策略权重规则配置（前端抽奖权重策略进度条(需要用户已抽奖次数/积分-userId)---抽奖次数/积分达到阈值，触发权重抽奖策略）
      curl --request POST \
      --url http://localhost:8091/api/v1/raffle/strategy/query_raffle_strategy_rule_weight \
      --header 'content-type: application/json' \
      --data '{
      "userId":"xiaofuge",
      "activityId": 100301
      }'
     *
     * {
     * 	"code": "0000",
     * 	"info": "调用成功",
     * 	"data": [
     * 		    {
     * 			"ruleWeightCount": 70,
     * 			"userActivityAccountTotalUseCount": 1,
     * 			"strategyAwards": [
     *                {
     * 					"awardId": 106,
     * 					"awardTitle": "轻奢办公椅"
     *                },
     *                {
     * 					"awardId": 107,
     * 					"awardTitle": "小霸王游戏机"
     *                }
     * 			]
     *        },
     *        {
     * 			"ruleWeightCount": 10,
     * 			"userActivityAccountTotalUseCount": 1,
     * 			"strategyAwards": [
     *                {
     * 					"awardId": 102,
     * 					"awardTitle": "OpenAI会员卡"
     *                },
     *                {
     * 					"awardId": 103,
     * 					"awardTitle": "支付优惠券"
     *                }
     * 			]
     *        },
     *        {
     * 			"ruleWeightCount": 1000,
     * 			"userActivityAccountTotalUseCount": 1,
     * 			"strategyAwards": [
     *                {
     * 					"awardId": 104,
     * 					"awardTitle": "小米台灯"
     *                },
     *                {
     * 					"awardId": 105,
     * 					"awardTitle": "小米su7周体验"
     *                }
     * 			]
     *        }
     * 	]
     * }
     */
    @RequestMapping(value = "query_raffle_strategy_rule_weight", method = RequestMethod.POST)
    @Override
    public Response<List<RaffleStrategyRuleWeightResponseDTO>> queryRaffleStrategyRuleWeight(@RequestBody RaffleStrategyRuleWeightRequestDTO request) {
        try {
            log.info("查询抽奖策略权重规则配置开始 userId:{} activityId：{}", request.getUserId(), request.getActivityId());
            // 1. 参数校验
            if (StringUtils.isBlank(request.getUserId()) || null == request.getActivityId()) {
                throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
            }
            // 2. 查询用户抽奖总次数(账号总活动库存表直接查)
            Integer userActivityAccountTotalUseCount = raffleActivityAccountQuotaService.queryRaffleActivityAccountPartakeCount(request.getActivityId(), request.getUserId());
            // 3. 查询策略权重规则
            // eg:一个策略有多个权重规则 (60:102 4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108)
            List<RaffleStrategyRuleWeightResponseDTO> raffleStrategyRuleWeightList = new ArrayList<>();
            List<RuleWeightVO> ruleWeightVOList = raffleRule.queryAwardRuleWeightByActivityId(request.getActivityId());
            for (RuleWeightVO ruleWeightVO : ruleWeightVOList) {
                // 转换对象
                List<RaffleStrategyRuleWeightResponseDTO.StrategyAward> strategyAwards = new ArrayList<>();
                List<RuleWeightVO.Award> awardList = ruleWeightVO.getAwardList();
                for (RuleWeightVO.Award award : awardList) {
                    RaffleStrategyRuleWeightResponseDTO.StrategyAward strategyAward = new RaffleStrategyRuleWeightResponseDTO.StrategyAward();
                    strategyAward.setAwardId(award.getAwardId());
                    strategyAward.setAwardTitle(award.getAwardTitle());
                    strategyAwards.add(strategyAward);
                }
                // 封装对象
                RaffleStrategyRuleWeightResponseDTO raffleStrategyRuleWeightResponseDTO = new RaffleStrategyRuleWeightResponseDTO();
                raffleStrategyRuleWeightResponseDTO.setRuleWeightCount(ruleWeightVO.getWeight());
                raffleStrategyRuleWeightResponseDTO.setStrategyAwards(strategyAwards);
                raffleStrategyRuleWeightResponseDTO.setUserActivityAccountTotalUseCount(userActivityAccountTotalUseCount);

                raffleStrategyRuleWeightList.add(raffleStrategyRuleWeightResponseDTO);
            }
            Response<List<RaffleStrategyRuleWeightResponseDTO>> response = Response.<List<RaffleStrategyRuleWeightResponseDTO>>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(raffleStrategyRuleWeightList)
                    .build();
            log.info("查询抽奖策略权重规则配置完成 userId:{} activityId：{} response: {}", request.getUserId(), request.getActivityId(), JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("查询抽奖策略权重规则配置失败 userId:{} activityId：{}", request.getUserId(), request.getActivityId(), e);
            return Response.<List<RaffleStrategyRuleWeightResponseDTO>>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }



    /**
     * 策略装配，将策略信息装配到缓存中
     * <a href="http://localhost:8091/api/v1/raffle/strategy_armory">/api/v1/raffle/strategy_armory</a>
     *
     * @param strategyId 策略ID
     * @return 装配结果
     */
    @Deprecated
    @RequestMapping(value = "strategy_armory", method = RequestMethod.GET)
    @Override
    public Response<Boolean> strategyArmory(@RequestParam Long strategyId) {
        try {
            log.info("抽奖策略装配开始 strategyId：{}", strategyId); // 方便上线后检查日志
            boolean armoryStatus = strategyArmory.assembleLotteryStrategy(strategyId);
            Response<Boolean> response = Response.<Boolean>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(armoryStatus)
                    .build();
            log.info("抽奖策略装配完成 strategyId：{} response: {}", strategyId, JSON.toJSONString(response));
            return response;
        } catch (Exception e) {
            log.error("抽奖策略装配失败 strategyId：{}", strategyId, e);
            return Response.<Boolean>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

    /**
     * 随机抽奖接口
     * <a href="http://localhost:8091/api/v1/raffle/strategy/random_raffle">/api/v1/raffle/random_raffle</a>
     *
     * @param requestDTO 请求参数 {"strategyId":1000001}
     * @return 抽奖结果
     */
    @Deprecated
    @RequestMapping(value = "random_raffle", method = RequestMethod.POST)
    @Override
    public Response<RaffleStrategyResponseDTO> randomRaffle(@RequestBody RaffleStrategyRequestDTO requestDTO) {
        try {
            log.info("随机抽奖开始 strategyId: {}", requestDTO.getStrategyId());
            // 调用抽奖接口
            RaffleAwardEntity raffleAwardEntity = raffleStrategy.performRaffle(RaffleFactorEntity.builder()
                    .userId("system")
                    .strategyId(requestDTO.getStrategyId())
                    .build());
            // 封装返回结果
            Response<RaffleStrategyResponseDTO> response = Response.<RaffleStrategyResponseDTO>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(RaffleStrategyResponseDTO.builder()
                            .awardId(raffleAwardEntity.getAwardId())
                            .awardIndex(raffleAwardEntity.getSort())
                            .build())
                    .build();
            log.info("随机抽奖完成 strategyId: {} response: {}", requestDTO.getStrategyId(), JSON.toJSONString(response));
            return response;
        } catch (AppException e) {
            log.error("随机抽奖失败 strategyId：{} {}", requestDTO.getStrategyId(), e.getInfo());
            return Response.<RaffleStrategyResponseDTO>builder()
                    .code(e.getCode())
                    .info(e.getInfo())
                    .build();
        } catch (Exception e) {
            log.error("随机抽奖失败 strategyId：{}", requestDTO.getStrategyId(), e);
            return Response.<RaffleStrategyResponseDTO>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

}
